using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Gj.Galaxy.Logic;
using SimpleJSON;
using TapSDK.Core;
using TapSDK.Compliance;
using TapSDK.Moment;
using UnityEngine;

namespace Gj.TapTap
{
    public class TapTap : PauseSystem, QuitSystem
    {
        // public delegate void OnConnectChatSuccessDelegate(string channel, int number);
        //
        //
        // public delegate void OnConnectDelegate();
        //
        // public delegate void OnListDelegate(string prefix, Conversation[] channels);
        //
        // public delegate void OnMessageDelegate(string channel, TDSUser target, string content, bool isSelf);
        //
        // public delegate void OnReconnectDelegate();
        //
        // public delegate void OnUpdateListDelegate(string prefix, TDSUser[] targets);
        //
        // public delegate void OnUpdateUnReadCountDelegate(string channel, int number);

        public static TapTap Instance;
        public static TapTapSettings settings;
        public static bool ImSuccess;
        public static bool isChina;
        public static bool NeedInit;
        public static bool FinishInit;


        static TapTap()
        {
            settings = LoadSettings();
            Instance = new TapTap();
        }

        // public void OnConnectSuccess(string channel, int number)
        // {
        //     if (OnConnectChatSuccessEvent != null) OnConnectChatSuccessEvent(channel, number);
        // }
        //
        // public void UpdateUnReadCount(string channel, int number)
        // {
        //     if (OnUpdateUnReadCountEvent != null) OnUpdateUnReadCountEvent(channel, number);
        // }
        //
        // public void OnMessage(string channel, TDSUser target, string message, bool isSelf)
        // {
        //     if (OnMessageEvent != null) OnMessageEvent(channel, target, message, isSelf);
        // }
        //
        // public void OnUpdateList(string prefix, TDSUser[] targets)
        // {
        //     if (OnUpdateListEvent != null) OnUpdateListEvent(prefix, targets);
        // }
        //
        // public void OnList(string prefix, Conversation[] channels)
        // {
        //     if (OnListEvent != null) OnListEvent(prefix, channels);
        // }
        //
        // public void OnReconnect()
        // {
        //     if (OnReconnectEvent != null) OnReconnectEvent();
        // }
        //
        // public void OnConnect()
        // {
        //     ImSuccess = true;
        //     if (OnConnectEvent != null) OnConnectEvent();
        // }

        public void OnPause()
        {
            Antiaddiction.Leave();
        }

        public void OnResume()
        {
            Antiaddiction.Enter();
        }

        public void OnQuit()
        {
            Antiaddiction.Leave();
        }
        //
        // public static event OnConnectDelegate OnConnectEvent;
        // public static event OnReconnectDelegate OnReconnectEvent;
        // public static event OnMessageDelegate OnMessageEvent;
        // public static event OnConnectChatSuccessDelegate OnConnectChatSuccessEvent;
        // public static event OnUpdateUnReadCountDelegate OnUpdateUnReadCountEvent;
        // public static event OnUpdateListDelegate OnUpdateListEvent;
        // public static event OnListDelegate OnListEvent;

        private static TapTapSettings LoadSettings()
        {
            var loadedSettings = (TapTapSettings)Resources.Load("TapTapSettings", typeof(TapTapSettings));
            if (loadedSettings == null)
            {
                loadedSettings = ScriptableObject.CreateInstance<TapTapSettings>();
                LogTools.Error("TapTapSettings is not exist (Resources)");
            }

            return loadedSettings;
        }

        public static async Task Init(ChannelInfo info)
        {
            if (settings == null) return;
            if (!NeedInit) return;
            if (FinishInit) return;
            FinishInit = true;
            LogTools.Process("taptap channel:"+info.isChina);
            // Debug.LogError("taptap domain:"+settings.ApiDomain);
            // var config = new TapConfig.Builder();

            if (info.isChina)
            {
                // config.ClientID(settings.ClientId) // 必须，开发者中心对应 Client ID
                //     .ClientToken(settings.ClientToken) // 必须，开发者中心对应 Client Token
                //     .ServerURL(settings.ApiDomain.Contains("https")
                //         ? settings.ApiDomain
                //         : "https://" + settings.ApiDomain) // 必须，开发者中心 > 你的游戏 > 游戏服务 > 基本信息 > 域名配置 > API
                //     .RegionType(RegionType.CN); // 非必须，CN 表示中国大陆，IO 表示其他国家或地区;
                isChina = true;
                // 适用于中国大陆
                // TapLogin.Init(settings.ClientId);
            }
            else
            {
                // config.ClientID(settings.IoClientId) // 必须，开发者中心对应 Client ID
                //     .ClientToken(settings.IoClientToken) // 必须，开发者中心对应 Client Token
                //     .ServerURL(settings.IoApiDomain.Contains("https")
                //         ? settings.IoApiDomain
                //         : "https://" + settings.IoApiDomain) // 必须，开发者中心 > 你的游戏 > 游戏服务 > 基本信息 > 域名配置 > API
                //     .RegionType(RegionType.IO);
                // 适用于其他国家或地区
                // TapLogin.Init(settings.IoClientId, false, true);
            }
            TapTapSdkOptions coreOptions = new TapTapSdkOptions
            {
                // 客户端 ID，开发者后台获取
                // clientId = settings.ClientId,
                // // 客户端令牌，开发者后台获取
                // clientToken = settings.ClientToken,
                // // 地区，CN 为国内，Overseas 为海外
                // region = TapTapRegionType.CN,
                // // 语言，默认为 Auto，默认情况下，国内为 zh_Hans，海外为 en
                // preferredLanguage = TapTapLanguageType.zh_Hans,
                // 是否开启日志，Release 版本请设置为 false
                enableLog = true,
            };
            if (info.isChina)
            {
                coreOptions.clientId = settings.ClientId;
                coreOptions.clientToken = settings.ClientToken;
                coreOptions.region = TapTapRegionType.CN;
                coreOptions.preferredLanguage = TapTapLanguageType.zh_Hans;
                coreOptions.clientPublicKey = settings.ClientPublicKey;
                // 合规认证配置
                TapTapComplianceOption complianceOption = new TapTapComplianceOption
                {
                    showSwitchAccount = true,
                    useAgeRange = true,
                };
// 其他模块配置项
                TapTapSdkBaseOptions[] otherOptions = new TapTapSdkBaseOptions[]
                {
                    complianceOption
                };
// TapSDK 初始化
                try
                {
                    TapTapSDK.Init(coreOptions, otherOptions);
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }

                try
                {
                    Antiaddiction.Init();
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            }
            else
            {
                coreOptions.clientId = settings.IoClientId;
                coreOptions.clientToken = settings.IoClientToken;
                coreOptions.region = TapTapRegionType.Overseas;
                coreOptions.preferredLanguage = TapTapLanguageType.Auto;
                // coreOptions.enableLog = true;
                // TapSDK 初始化
                try
                {
                    TapTapSDK.Init(coreOptions);
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            }
            #if UNITY_STANDALONE
            bool IsSuccess = await TapTapSDK.IsLaunchedFromTapTapPC();
            if (IsSuccess)
            {
                UnityEngine.Debug.Log(" TapTap PC 端校验通过");
                // TODO: 继续后续登录等其他业务流程
            }
            else
            {

            }
            #endif
        }

        public static async void Login(GamePlayer player)
        {
            if (isChina)
            {
                // 重新登录taptap， sessionToken是海外版
                // var config = new TapConfig.Builder();
                // config.ClientID(settings.IoClientId) // 必须，开发者中心对应 Client ID
                //     .ClientToken(settings.IoClientToken) // 必须，开发者中心对应 Client Token
                //     .ServerURL(settings.IoApiDomain.Contains("https")
                //         ? settings.IoApiDomain
                //         : "https://" + settings.IoApiDomain) // 必须，开发者中心 > 你的游戏 > 游戏服务 > 基本信息 > 域名配置 > API
                //     .RegionType(RegionType.IO);
                // TapBootstrap.Init(config.ConfigBuilder());
            }

            var info = player.Instance;
            // var sessionToken = info["sessionToken"];
            // // Debug.LogError("login session:"+sessionToken);
            // await TDSUser.BecomeWithSessionToken(sessionToken);
            // // Debug.LogError("login session:"+sessionToken+" success");
            //
            // var currentUser = await TDSUser.GetCurrent();
            // await Im.Init(currentUser, Instance);
            // Debug.LogError("taptap login"+currentUser.ObjectId);

            Game.single.RegisterPause(Instance);
            Game.single.RegisterQuit(Instance);
            Antiaddiction.Enter();
            // await Im.JoinChannel("global");
            // await Task.Delay(2000);
            // await Im.Send("global", "new"+TimeTools.CurrentSecond());
        }

        public static void Scene(string sceneId)
        {
            Debug.LogError(TapTapMoment.Version);
            TapTapMoment.OpenScene(sceneId);
        }

        public static void Event(string en, Dictionary<string, object> param)
        {
            if (!FinishInit) return;
            var info = new JSONObject();
            var e = param.GetEnumerator();
            while (e.MoveNext())
            {
                info[e.Current.Key] = e.Current.Value.ToString();
            }
            e.Dispose();
            TapTapEvent.LogEvent(en, info.ToString());
        }
    }
}